var appPath = getAppPath();	

$(function(){
	// 主的分类(检索用)
	$("#queryTmplType").combobox({
		url:appPath+'/itbStats/getTypeForCombo.action?topIds=1,2,3,4,6,7,8,1010,1011&blkFlg=1',
		valueField:'type_id',//默认为不选选了后将参数传给type_id
		textField:'type_name',
		onSelect:function(selRecd){
			$("#queryTmplType2").combobox("clear");
			$("#queryTmplType3").combobox("clear");
			$("#queryTmplType2").combobox("loadData",{});
			$("#queryTmplType3").combobox("loadData",{});	
			// 中间分类
			var parentId=selRecd.type_id;
			if(Number(parentId)>0){
				$("#queryTmplType2").combobox({
					url:appPath+'/itbStats/getTypeForCombo.action?parent='+parentId+'&blkFlg=1',
					valueField:'type_id',
					textField:'type_name',
					onSelect:function(selRecd2){
						$("#queryTmplType3").combobox("clear");
						$("#queryTmplType3").combobox("loadData",{});
						
						// 小分类
						var parentId2=selRecd2.type_id;
						if(Number(parentId2)>0){
							$("#queryTmplType3").combobox({
								url:appPath+'/itbStats/getTypeForCombo.action?parent='+parentId2+'&blkFlg=1',
								valueField:'type_id',
								textField:'type_name',
								onSelect:function(selRecd3){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});
	
	// 主的分类(设置用)
	$("#batchType").combobox({
		url:appPath+'/itbStats/getTypeForCombo.action?topIds=1,2,3,4,6,7,8,9,1010,1011',
		valueField:'type_id',
		textField:'type_name',
		onSelect:function(selRecd){
			$("#batchType2").combobox("clear");
			$("#batchType3").combobox("clear");
			$("#batchType2").combobox("loadData",{});
			$("#batchType3").combobox("loadData",{});	
			// 中间分类
			var parentId=selRecd.type_id;
			if(Number(parentId)>0){
				$("#batchType2").combobox({
					url:appPath+'/itbStats/getTypeForCombo.action?parent='+parentId,
					valueField:'type_id',
					textField:'type_name',
					onSelect:function(selRecd2){
						$("#batchType3").combobox("clear");
						$("#batchType3").combobox("loadData",{});
						
						// 小分类
						var parentId2=selRecd2.type_id;
						if(Number(parentId2)>0){
							$("#batchType3").combobox({
								url:appPath+'/itbStats/getTypeForCombo.action?parent='+parentId2,
								valueField:'type_id',
								textField:'type_name',
								onSelect:function(selRecd3){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});
	
	$("#queryUserId").combobox({
		url:appPath+'/itbCoupon/getOrgUserForCombo.action?blkFlg=1&orgId=1',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdU){
			// TODO
		}
	});
	
	// 检索日期范围
	$("#queryDateStart").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	$("#queryDateEnd").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	initJspGrid();
});
function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);//格式化mm-dd
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 样版列表初始化
function initJspGrid(){
	$('#tmplGrid').datagrid({
	    url:appPath + "/itbStats/getMapInfoList.action",
	    height:'full',
	    remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
			//微缩图
		    {field:'thumb',title:'缩略图',width:90,align:'center',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.thumb) {
	        			retUrl = '<a href="' + rowData.thumb + '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:120px;width:100%">'
	        				+ '<span style="display:table-cell;vertical-align:middle">'
	        				+ '<img src="' + rowData.thumb+'?x-oss-process=image/resize,m_lfit,h_120,w_100'
	        				+ '" style="display:inline;max-height:110px;max-width:128px"></span></div></a>';
	        		}
	        		return retUrl;
	        	}},
	        {field:'design_id',title:'模版ID',width:55,align:'center',sortable:false},
	        {field:'numbers',title:'应用次数',width:55,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<span style="color:red">'+Number(value||'0')+'</span>';
	        	}
	        },
	        {field:'applyCnt',title:'<span style="color:blue">显示次数</span>',width:55,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<a href="javascript:void(0)" onclick="editApplyCnt('+rowData.stats_id+','+rowData.applyCnt+')"><span style="color:blue;">'+Number(value||'0')+'</span></a>';
	        	}
	        },
	        {field:'coll_num',title:'收藏次数',width:55,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<span style="color:green">'+Number(value||'0')+'</span>';
	        	}
	        },
	        {field:'order_num',title:'下单次数',width:55,align:'center',sortable:true,
	        	formatter:function(value, rowData, rowIndex){
	        		return '<span style="color:red">'+Number(value||'0')+'</span>';
	        	}
	        },
		    {field:'top_type',title:'主分类',width:50,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  var tn = '<span style="color:red">未知</span>';
		    		  switch(Number(value||'0')){
		    		  	case 1: tn='海报';break;
		    		  	case 2: tn='多页';break;
		    		  	case 3: tn='PPT';break;
		    		  	case 4: tn='印品';break;
		    		  	case 6: tn='社交媒体';break;
		    		  	case 7: tn='电商';break;
		    		  	case 8: tn='微商';break;
		    		  	case 1010: tn='LOGO商品';break;
		    		  	case 1011: tn='营销商品';break;
		    		  	case 1030: tn= '视频背景';break;
		    		  }
		    		  return tn;
		    	  }
		      },
			{field:'editType',title:'子分类',width:55,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
					  return rowData.type_name || '<span style="color:red">未分类</span>';
				  }
			},
		    {field:'design_name',title:'设计模版名称',width:110,align:'left',sortable:false},
		    {field:'nickname',title:'设计师',width:65,align:'left',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return '<font color="green">ID:'+rowData.user_id+'</font></br>'+value+'';
		    	}
		    },
		    {field:'size_id',title:'尺寸',width:55,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return 'w:'+(rowData.width||'N/A')+'<br/>*<br/>h:'+(rowData.height||'N/A')+'';
		    	  }
		    },			        
		    {field:'create_time',title:'创建时间',width:70,align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		console.log(value);
					return '<span style="display:block;white-space:pre-wrap;">'+value+'</span>';
	        	}
		    },			        
		    {field:'update_time',title:'更新时间',width:70,align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
					return '<span style="display:block;white-space:pre-wrap;">'+value+'</span>';
	        	}
		    }
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar: [
          {
			text:'刷新APP端模版应用次数',
			iconCls:'icon-reload',
			handler:function(){
				showRefreshDlg();
			}
		  },
		  '-',
		  {
		    text:'批量设置应用次数',
		    iconCls:'icon-reload',
		    handler:function(){
		    	showBatchDlg();
		    }
		  }
        ]
	});
}

/*
 * 编辑修改 显示用应用次数
 */
function editApplyCnt(s_id,order){
	$("#viewId").val(s_id);
	$("#viewContent").val(order);
	
	$("#viewBtn").show();
	$('#viewDlg').window({
		title:'编辑[显示用]应用次数',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#viewDlg').window('move',{top:20,left:40});
	$('#viewDlg').window('open',{top:100,left:120});
}

//取消浏览 显示用应用次数
function cancleEditView(){
	$("#viewDlg").window('close');
}

//确定编辑 显示用应用次数
function doEditView(){
	var id=$("#viewId").val();//这条记录的id
	var applyCnt=$("#viewContent").val();//获取输入的浏览次数
	if(!applyCnt || applyCnt.length == 0|| Number(applyCnt)<=0){
		$.messager.alert('提示信息','输入有效数字','warning');
		return;
	}
	var url=appPath+"/itbStats/editApplyCnt.action?id="+id+"&applyCnt="+applyCnt;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','修改成功！','info',function(){
				doQuery();
				$('#viewDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','修改失败','warning');
		}
	});
	
}


function showRefreshDlg() {
	$("#refreshBtn").show();
	$('#refreshDlg').window({
		title:'刷新APP端模版［应用次数］显示数据',
		iconCls:'icon-reload',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#refreshDlg').window('move',{top:20,left:20});
	$('#refreshDlg').window('open');
}
function cancelRefresh() {
	$('#refreshDlg').window('close');
}
function doRefresh() {
	var type =$("#refreshType").combobox('getValue');
	
	$.loading(true);
	var url = getApiServer()+"/callFunc/setTmplApplyCnt?type="+type;
	$.post(url,function(ret){
		$.loading(false);
		if(ret.success){
			$.messager.alert('提示信息','处理模版总数:'+ret.data.GetCnt+
					'<br/>新建:'+ret.data.InsCnt+'  更新:'+ret.data.UpdCnt+
					'<br/>错误:'+ret.data.ErrCnt, 'warning');
		}else {
			$.messager.alert('提示信息','刷新失败！','warning');
		}
	});
}


function showBatchDlg() {
	$("#batchBtn").show();
	$('#batchDlg').window({
		title:'批量设置［应用次数］显示数据',
		iconCls:'icon-reload',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#batchDlg').window('move',{top:20,left:20});
	$('#batchDlg').window('open');
}
function cancelBatchUpd() {
	$('#batchDlg').window('close');
}
function doBatchUpd() {
	var top_type =Number($("#batchType").combobox('getValue')||'0')||0;
	var type =Number($("#batchType3").combobox('getValue')||'0')||0;
	var base =$("#batchBaseCnt").combobox('getValue');
	var mult=Number($("#batchMult").val()||'0')||0;
	
	if(!mult || mult<=1 || mult>21){
		$.messager.alert('提示信息','请输入有效倍数!</br><span style="color:red">注: 1<倍数<=21(最好不要设置10或20)</span>','warning');
		return;
	}
	
	if(top_type!=3) {
		// 非ppt需要指定小分类
		if(!type || type<=0) {
			$.messager.alert('提示信息','非PPT模版,请指定小分类!','warning');
			return;
		} else {
			batchUpdProc();
		}
	} else {
		// ppt
		$.messager.confirm('确定','<span style="color:red">PPT模版将忽略子分类,全部更新!</span></br>是否确认更新？',function(r){
			if(r) {
				batchUpdProc();
			}
		});
	}
	
	function batchUpdProc() {
		$.loading(true);
		var url = appPath+"/itbStats/batchSetTmplApplyCnt.action?top_type="+top_type+"&type="+type+"&base="+base+"&mult="+mult;
		$.post(url,function(ret){
			$.loading(false);
			if(ret=="ok"){
				$.messager.alert('提示信息','设置成功', 'warning');
				doQuery();
			}else {
				$.messager.alert('提示信息','设置失败！','warning');
			}
		});
	}
}


function getQueryParam(){
	var queryObject = {};
	var findDtS = $("#queryDateStart").datebox('getValue');//获取开始结束日期
	var findDtE = $("#queryDateEnd").datebox('getValue');
	var findPub = $("#queryPublish").combobox('getValue');
	var findTmplType =$("#queryTmplType3").combobox('getValue');
	if(!findTmplType){
		findTmplType =$("#queryTmplType2").combobox('getValue');
	}
	var findTmplTypetop=$("#queryTmplType").combobox('getValue');					
	var findDocName=$("#queryDocName").val().trim();//文档名字	
	if (findTmplType) {
		queryObject.findTmplType = findTmplType;// 类型
	}
	if (findTmplTypetop) {
		queryObject.findTmplTypetop = findTmplTypetop;// 类型
	}
	
	var fingUserId = $("#queryUserId").combobox('getValue');
	
	var findDesignerName = $("#queryDesigername").val();// 根据设计者名字 模糊搜素
	if (findDesignerName && findDesignerName.length>0) queryObject.findDesignerName = findDesignerName;
	if (Number(fingUserId)>0) queryObject.findUserId = fingUserId;// 查找用户ID
	if(findPub&&findPub.length>0) queryObject.findPubFlg = findPub;// 发布标记
	if(findDocName&&findDocName.length>0) queryObject.findDocName = findDocName;// 样版名称
	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS + ' 00:00:00 ';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59 ';
	return queryObject;
}
/**
 * 查询数据
 */
function doQuery(){
	$("#tmplGrid").datagrid('unselectAll');
	$("#tmplGrid").datagrid('reload',getQueryParam());
	var findDtS = $("#queryDateStart").datebox('getValue');//获取开始结束日期前
	var findDtE = $("#queryDateEnd").datebox('getValue');
	if(findDtS && findDtS.length>0){
		var chkRet = chkInputDate(findDtS);
		$("#queryDateStart").datebox('setValue',chkRet);
	}
	if(findDtE && findDtE.length>0){
		var chkRet = chkInputDate(findDtE);
		$("#queryDateEnd").datebox('setValue',chkRet);
	}
}